package com.recharge.controller;

import com.alibaba.fastjson.JSON;
import com.recharge.ExceptionEnum;
import com.recharge.OrderService;
import com.recharge.controller.jd.JdMapping;
import com.recharge.domain.TradeMerchant;
import com.recharge.domain.TradeOrder;
import com.recharge.mapper.ITradeMerchantMapper;
import com.recharge.mapper.ITradeOrderMapper;
import com.recharge.utils.HttpClientUtils;
import com.recharge.utils.OrderStatus;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by CAOQI on 2017/2/2.
 */
@Controller
@RequestMapping("/api")
public class ApiController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OrderService orderService;

    @Autowired
    private ITradeMerchantMapper iTradeMerchantMapper;
    
    @Autowired
    private ITradeOrderMapper iTradeOrderMapper;

    @RequestMapping("/merchant/balance")
    @ResponseBody
    public ResponseInfo balance(@RequestParam("merchantId")String merchantId,
                                @RequestParam("md5Key")String md5Key){

        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setEnum(ExceptionEnum.SUB_SUCCESS);

        logger.info("balance request,merchantId:{} , md5Key:{}",merchantId,md5Key);
        TradeMerchant tradeMerchant = iTradeMerchantMapper.selectInfoByMd5Key(merchantId, md5Key);

        if (tradeMerchant!=null){
            Map<String,String> data = new HashMap<String, String>();
            data.put("balance",tradeMerchant.getBalance().toString());
            responseInfo.setData(JSON.toJSONString(data));
        }
        return responseInfo;
    }

    @RequestMapping("/ll/makeOrder")
    @ResponseBody
    public ResponseInfo llMakeOrder(LlMakeOrderForm llMakeOrderForm){

        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setEnum(ExceptionEnum.SUB_SUCCESS);

        logger.info("makeOrder request. {}",JSON.toJSONString(llMakeOrderForm));
        TradeMerchant tradeMerchant = iTradeMerchantMapper.selectById(
                llMakeOrderForm.getMerchantId());
        
        TradeOrder tradeOrder = iTradeOrderMapper.selectByMerOrderId(
        		llMakeOrderForm.getMerOrderId());
        if(tradeOrder != null){
        	if(StringUtils.equals(llMakeOrderForm.getMerOrderId(),tradeOrder.getMerId())){
            	responseInfo.setEnum(ExceptionEnum.ORDER_EXIST);
                return responseInfo;
            }
        }
        
        if (!StringUtils.equals(DigestUtils.md5Hex(llMakeOrderForm.getSignString()+tradeMerchant.getMd5Key()),llMakeOrderForm.getSign())){
            responseInfo.setEnum(ExceptionEnum.SIGN_ERROR);
            return responseInfo;
        }

        try {
            orderService.makeOrder(llMakeOrderForm.getMerchantId(),Short.parseShort(llMakeOrderForm.getIspId()),
                    Short.parseShort(llMakeOrderForm.getProvinceId()),
                    "",llMakeOrderForm.getChargeNumber(),Long.parseLong(llMakeOrderForm.getChargeMoney()),llMakeOrderForm.getMerOrderId(),
                    llMakeOrderForm.getNotifyUrl(),Short.parseShort(llMakeOrderForm.getBusiType()),0L,new BigDecimal(0),llMakeOrderForm.getPackType(),"LL");
        } catch (Exception e) {
            logger.error("system error",e);
            responseInfo.setEnum(ExceptionEnum.SYS_ERROR);
        }
        return responseInfo;
    }



    @RequestMapping("/hf/makeOrder")
    @ResponseBody
    public ResponseInfo hfMakeOrder(HfMakeOrderForm hfMakeOrderForm){

        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setEnum(ExceptionEnum.SUB_SUCCESS);

        logger.info("makeOrder request. {}",JSON.toJSONString(hfMakeOrderForm));
        TradeMerchant tradeMerchant = iTradeMerchantMapper.selectById(
                hfMakeOrderForm.getMerchantId());

        if (!StringUtils.equals(DigestUtils.md5Hex(hfMakeOrderForm.getSignString()+tradeMerchant.getMd5Key()),hfMakeOrderForm.getSign())){
            responseInfo.setEnum(ExceptionEnum.SIGN_ERROR);
            return responseInfo;
        }
        TradeOrder tradeOrder = iTradeOrderMapper.selectByMerOrderId(
                hfMakeOrderForm.getMerOrderId());

        if(tradeOrder != null){
        	if(StringUtils.equals(hfMakeOrderForm.getMerOrderId(),tradeOrder.getMerId())){
                responseInfo.setEnum(ExceptionEnum.ORDER_EXIST);
                return responseInfo;
            }
        }

        try {
            orderService.makeOrder(hfMakeOrderForm.getMerchantId(),Short.parseShort(hfMakeOrderForm.getIspId()),
                    Short.parseShort(hfMakeOrderForm.getProvinceId()),
                    "",hfMakeOrderForm.getChargeNumber(),Long.parseLong(hfMakeOrderForm.getChargeMoney()),hfMakeOrderForm.getMerOrderId(),
                    hfMakeOrderForm.getNotifyUrl(),Short.parseShort("0"),0L,new BigDecimal(0),"0","HF");
        } catch (Exception e) {
            logger.error("system error",e);
            responseInfo.setEnum(ExceptionEnum.SYS_ERROR);
        }
        return responseInfo;
    }

    @RequestMapping("/hf/queryorder")
    @ResponseBody
    public ResponseInfo hfQueryOrder(@RequestParam("merOrderId")String merOrderId,@RequestParam("merchantId")String merchantId,
                                   @RequestParam("sign")String sign){
        ResponseInfo responseInfo = new ResponseInfo();
        responseInfo.setEnum(ExceptionEnum.SUB_SUCCESS);

        logger.info("queryOrder request . merchantId:{}, merOrderId:{} ,sign:{}",merchantId,merOrderId,sign);
        TradeMerchant tradeMerchant = iTradeMerchantMapper.selectById(merchantId);

        if (!StringUtils.equals(DigestUtils.md5Hex("merchantId"+merchantId+"merOrderId"+ merOrderId + tradeMerchant.getMd5Key()),sign)){
            responseInfo.setEnum(ExceptionEnum.SIGN_ERROR);
            return responseInfo;
        }
        TradeOrder  tradeOrder = iTradeOrderMapper.selectByMerOrderId(merOrderId);
        Map<String, String> map = new HashMap<String, String>();
        if(tradeOrder ==null){
            responseInfo.setEnum(ExceptionEnum.ORDER_NOT_EXIST);
        }else if(tradeOrder.getOrderStatus()==OrderStatus.SUCCESS){
            map.put("orderStatus", ""+OrderStatus.SUCCESS);
            map.put("orderId", tradeOrder.getOrderId());

        }else if(tradeOrder.getOrderStatus()==OrderStatus.FAIL){
            map.put("orderStatus", ""+OrderStatus.FAIL);
            map.put("orderId", tradeOrder.getOrderId());
        }else{
            map.put("orderStatus", ""+OrderStatus.PROCESSING);
            map.put("orderId", tradeOrder.getOrderId());
        }
        String josn = JSON.toJSONString(map);
        responseInfo.setData(josn);
        return responseInfo;
    }
    
    @RequestMapping("/ll/queryorder")
    @ResponseBody
    public ResponseInfo llQueryOrder(@RequestParam("merOrderId")String merOrderId,@RequestParam("merchantId")String merchantId,
    		@RequestParam("sign")String sign){
    	ResponseInfo responseInfo = new ResponseInfo();
    	responseInfo.setEnum(ExceptionEnum.SUB_SUCCESS);

        logger.info("queryOrder request . merchantId:{}, merOrderId:{} ,sign:{}",merchantId,merOrderId,sign);
        TradeMerchant tradeMerchant = iTradeMerchantMapper.selectById(merchantId);
        
    	if (!StringUtils.equals(DigestUtils.md5Hex("merchantId"+merchantId+"merOrderId"+ merOrderId + tradeMerchant.getMd5Key()),sign)){
            responseInfo.setEnum(ExceptionEnum.SIGN_ERROR);
            return responseInfo;
        }
    	TradeOrder  tradeOrder = iTradeOrderMapper.selectByMerOrderId(merOrderId);
    	Map<String, String> map = new HashMap<String, String>();
        if(tradeOrder ==null){
            responseInfo.setEnum(ExceptionEnum.ORDER_NOT_EXIST);
        }else if(tradeOrder.getOrderStatus()==OrderStatus.SUCCESS){
    		map.put("orderStatus", ""+OrderStatus.SUCCESS);
    		map.put("orderId", tradeOrder.getOrderId());
    		
    	}else if(tradeOrder.getOrderStatus()==OrderStatus.FAIL){
    		map.put("orderStatus", ""+OrderStatus.FAIL);
    		map.put("orderId", tradeOrder.getOrderId());
    	}else{
    		map.put("orderStatus", ""+OrderStatus.PROCESSING);
    		map.put("orderId", tradeOrder.getOrderId());
    	}
    	String josn = JSON.toJSONString(map);
    	responseInfo.setData(josn);
    	return responseInfo;
    }
    
    public static void main(String[] args) {
    	Map<String, String> map = new HashMap<String, String>();
    	map.put("merOrderId", "3026562424045012");
    	map.put("merchantId", "2881802543");
    	map.put("sign", DigestUtils.md5Hex("merchantId"+"2881802543"+"merOrderId"+ "3026562424045012" + "wenguitxzyd1237asdloowqe") );
    	String result = null;
    	try {
    		result = HttpClientUtils.invokePostHttp("http://localhost:8080/recharge-center-web/api/ll/queryorder", map, "UTF-8", 3000);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    	System.out.println(result);
	}
}
